package pe.prototipo.multiplayer.server;

import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class PEPrototipoMultiplayerServer {

    private static int port = 5000;
    private static String ip1 = "";
    private static String ip2 = "";

    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(port);
            while (true) {
                Socket socket = serverSocket.accept();
                if (ip1.equals("")){
                    ip1 = socket.getInetAddress().toString().substring(1);
                    System.out.println("Dirección IP1 guardada: " + ip1);
                    
                    OutputStream outputStream = socket.getOutputStream();
                    ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
                    objectOutputStream.writeObject(1);
                    objectOutputStream.close();
                } else if (ip2.equals("")){
                    ip2 = socket.getInetAddress().toString().substring(1);
                    System.out.println("Dirección IP2 guardada: " + ip2);
                    
                    OutputStream outputStream = socket.getOutputStream();
                    ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
                    objectOutputStream.writeObject(-1);
                    objectOutputStream.close();
                } 
                
                if (!ip1.equals("") && !ip2.equals("")){
                    Socket socket1 = new Socket(ip1, 5001);
                    Socket socket2 = new Socket(ip2, 5001);
                    
                    OutputStream outputStream = socket1.getOutputStream();
                    ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
                    objectOutputStream.writeObject(ip2);
                    objectOutputStream.close();
                    
                    outputStream = socket2.getOutputStream();
                    objectOutputStream = new ObjectOutputStream(outputStream);
                    objectOutputStream.writeObject(ip1);
                    objectOutputStream.close();
                    System.out.println("Clientes enlazados");
                    ip1 = "";
                    ip2 = "";
                }
            }
        } catch (Exception e) {
            System.out.println("PEPrototipoMultiplayerServer::main");
            System.out.println(e.toString());
        }
    }
}
